package com.alcatel_lucent.osp.action;

import com.alcatel_lucent.osp.model.*;
import com.alcatel_lucent.osp.service.*;
import net.sf.json.JSONSerializer;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.struts2.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: Guoshun Wu
 * Date: 13-9-7
 * Time: 下午9:13
 */
public class ViewRequestAction extends BaseAction {

    // Input and output request parameter
    private Long id;
    private Integer viewMode;
    private Integer category;

    // output parameter
    private Request request;
    private String requestJSON;
    private Map<String, String> copyList = new TreeMap<String, String>();

    public static final int VIEW_MODE_REQUEST = 1;
    public static final int VIEW_MODE_FOLLOWUP = 2;
    public static final int VIEW_MODE_EMAIL = 3;

    private String templatePageName = "viewDefaultRequestAttr";

    @Autowired
    private JSONService jsonService;

    public String getRequestJSON() {
        return requestJSON;
    }

    public ViewRequestAction() {
    }

    private RequestService requestService;
    private DaoService dao;

    @Autowired
    public void setRequestService(RequestService requestService) {
        this.requestService = requestService;
    }

    @Autowired
    public void setDao(DaoService dao) {
        this.dao = dao;
    }


    public Integer getViewMode() {
        return viewMode;
    }

    public void setViewMode(Integer viewMode) {
        this.viewMode = viewMode;
    }

    public Integer getCategory() {
        return category;
    }

    public void setCategory(Integer category) {
        this.category = category;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Request getReq() {
        return request;
    }

    public Collection<Category> getCategories() {
        return dao.retrieve("from Category");
    }

    public Collection<Type> getTypes() {
        if (category != null) return dao.retrieve("select c.types from Category c where c.id=" + category);
        return new ArrayList<Type>();
    }

    public Map<String, String> getCopyList() {
        return copyList;
    }

    public Collection<RequestStatus> getRequestStatus() {
        if (null != viewMode && VIEW_MODE_REQUEST == viewMode) {
            return RequestStatus.CLOSED == request.getStatus() ?
                    Arrays.asList(request.getStatus()) :
                    Arrays.asList(request.getStatus(), RequestStatus.CLOSED);
        }
        return Arrays.asList(RequestStatus.values());
    }

    /**
     * Test if request is opened by an guest(neither owner nor requester)
     */
    public boolean isGuest() {
        return requestService.isGuestAccess(request);
    }

    @Override
    public String execute() throws Exception {
        if (null != id) {
            request = requestService.findRequestById(id);
            Collections.sort((List<Comment>) request.getComments(), new Comparator<Comment>() {
                @Override
                public int compare(Comment c1, Comment c2) {
                    return (int) (c2.getCreateTime().getTime() - c1.getCreateTime().getTime());
                }
            });

            Collection<User> copyList = request.getCopyList();

            for (User user : copyList) {
                this.copyList.put(user.getCsl(), String.format("%s <%s>", user.getCil(), user.getEmail()));
            }

            Page page = (Page) dao.retrieve(Page.class, new PageId(request.getCategory().getId(), request.getType().getId(), "view"));
            if (null != page) {
                this.templatePageName = page.getName();
            }
            log.info("view request action {}", System.currentTimeMillis());
            requestJSON = requestService.getRequestJSONById(id, Arrays.asList(
                    "^.*attachments\\[\\d+\\]\\.content$",
                    "(?:type|lastUpdateBy|reportBy|(?:comments\\[\\d+\\].creator)|copyList\\[\\d+\\]).categories.*",
                    "category.(?:owner|type)s.*"
            ));
        }

//        log.info("requestJSON = {}", requestJSON);
        return SUCCESS;
    }

    public List<String> getProjectManagers() throws IOException {
        return (List<String>) readJSONResource(JSONServiceImpl.PROJECT_MANAGER);
    }

    public Map<String, String> getComponentAndReleases() throws IOException {
        return (Map<String, String>) readJSONResource(JSONServiceImpl.COMPONENT_AND_RELEASE);
    }

    public Map<String, String> getChangeProjects() throws IOException {
        return (Map) readJSONResource(JSONServiceImpl.PWD_TO_LOCAL);
    }

    public Map<String, String> getDisableProjects() throws IOException {
        return(Map) readJSONResource(JSONServiceImpl.PROJECT_TO_DISABLE);
    }

    private Object readJSONResource(String resourceKey) throws IOException {
        Map<String, String> postData = new HashMap<String, String>();
        postData.put(JSONServiceImpl.RESOURCE_NAME_KEY, resourceKey);
        return jsonService.getJSONResource(postData);
    }

    public Map<String, String> getProgramMappingExt(){
        return RequestServiceImpl.rd360ProgramTypeMapping;
    }


    public String getTemplatePageName() {
        return templatePageName;
    }

    public void setTemplatePageName(String templatePageName) {
        this.templatePageName = templatePageName;
    }
}
